/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fleet.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fleet.entity.Inspection;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fleet.entity.Surance;
import com.jeeplus.modules.fleet.service.SuranceService;

/**
 * 车队保险Controller
 * @author 李超辉
 * @version 2019-03-14
 */
@Controller
@RequestMapping(value = "${adminPath}/fleet/surance")
public class SuranceController extends BaseController {

	@Autowired
	private SuranceService suranceService;
	
	@ModelAttribute
	public Surance get(@RequestParam(required=false) String id) {
		Surance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = suranceService.get(id);
		}
		if (entity == null){
			entity = new Surance();
		}
		return entity;
	}
	
	/**
	 * 车队保险列表页面
	 */
	@RequiresPermissions("fleet:surance:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fleet/suranceList";
	}
	
		/**
	 * 车队保险列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:surance:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Surance surance, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!"总部".equals(pro)){
			surance.setPro(pro);
		}
		Page<Surance> page = suranceService.findPage(new Page<Surance>(request, response), surance);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑车队保险表单页面
	 */
	@RequiresPermissions(value={"fleet:surance:view","fleet:surance:add","fleet:surance:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Surance surance, Model model) {
		String pro= UserUtils.getUseroffice();
		if(surance.getIsNewRecord()){
			if(!"总部".equals(pro)){
				surance.setPro(pro);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			surance.setCode(code);
			List<Surance> list=suranceService.findList(surance);
			if(list==null||list.size()<1){
				surance.setCode(code+"001"+"BX");
			}else{
				if(list.size()/10==0){
					surance.setCode(code+"00"+(list.size()+1)+"BX");
				}else
				if(list.size()/100==0){
					surance.setCode(code+"0"+(list.size()+1)+"BX");
				}else{surance.setCode(code+(list.size()+1)+"BX");}

			}
		}
		model.addAttribute("surance", surance);
		return "modules/fleet/suranceForm";
	}

	/**
	 * 保存车队保险
	 */
	@ResponseBody
	@RequiresPermissions(value={"fleet:surance:add","fleet:surance:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Surance surance, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, surance)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		suranceService.save(surance);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存车队保险成功");
		return j;
	}
	
	/**
	 * 删除车队保险
	 */
	@ResponseBody
	@RequiresPermissions("fleet:surance:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Surance surance, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		suranceService.delete(surance);
		j.setMsg("删除车队保险成功");
		return j;
	}
	
	/**
	 * 批量删除车队保险
	 */
	@ResponseBody
	@RequiresPermissions("fleet:surance:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			suranceService.delete(suranceService.get(id));
		}
		j.setMsg("删除车队保险成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fleet:surance:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Surance surance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "车队保险"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Surance> page = suranceService.findPage(new Page<Surance>(request, response, -1), surance);
    		new ExportExcel("车队保险", Surance.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出车队保险记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fleet:surance:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Surance> list = ei.getDataList(Surance.class);
			for (Surance surance : list){
				try{
					suranceService.save(surance);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条车队保险记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条车队保险记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入车队保险失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/surance/?repage";
    }
	
	/**
	 * 下载导入车队保险数据模板
	 */
	@RequiresPermissions("fleet:surance:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "车队保险数据导入模板.xlsx";
    		List<Surance> list = Lists.newArrayList(); 
    		new ExportExcel("车队保险数据", Surance.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/surance/?repage";
    }

}